#!/bin/sh
#This Source Code Form is subject to the terms of the Mozilla
#Public License, v. 2.0. If a copy of the MPL was not distributed
#with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

check_mac_ver(){
        MACVER=$(sw_vers -productVersion)
        i=1
        for v in $(echo $MACVER | tr "." "\n")
        do
                if [ $i -eq 1 ]; then
                        if [ ! $v -eq 10 ]; then
                                break
                        fi
                else
                        if [ $v -lt 7 ]; then
                                return 1
                        fi
                        break
                fi
                ((i=i+1))
        done
        return 0
}

check_py_ver(){
	if [ "$1" ]; then
		if [ -f "$1" ]; then
			PYVER=$($1 --version 2>&1)
			PYV=$(echo $PYVER | sed 's/.* \([0-9]\).\([0-9]*\).*/\1\2/')
			if [ "$PYV" -ge "36" ] || [ "$PYV" -eq "27" ]; then				
				return 0
			fi
		fi
	fi
	return 1
}


PATH_DWA="$1"
PATH_DWA_NATIVE="$PATH_DWA/native"
PATH_DWA_RUNTIME="$PATH_DWA/runtime/bin"
PATH_DWA_RUNTIME_LIBRARY="$PATH_DWA/runtime/lib"

cd "${PATH_DWA}"	
check_mac_ver
if [ "$?" = "0" ]; then
	EXENM="dwagent"
	if [ -f "${PATH_DWA}/install.json" ]; then
		EXEAP=`grep \"name\" "${PATH_DWA}/install.json" | cut -d ':' -f 2 | cut -d '"' -f 2 | tr '[A-Z]' '[a-z]'`
		if [ $? -gt 0 ]; then
			exit 1
		fi
		if [ ! -z "${EXEAP}" ]; then
			EXENM=${EXEAP}
			mv "${PATH_DWA_RUNTIME}/dwagent" "${PATH_DWA_RUNTIME}/$EXENM"		
		fi
	fi
	#BIGSUR FIX
	if [ -f "${PATH_DWA_RUNTIME_LIBRARY}/libz.1.dylib" ]; then
		unlink "${PATH_DWA_RUNTIME_LIBRARY}/libz.1.dylib"
	fi
	export DYLD_LIBRARY_PATH=${PATH_DWA_RUNTIME_LIBRARY}
	if [ -z "$3" ] && [ -z "$4" ] && [ -z "$5" ] && [ -z "$6" ] && [ -z "$7" ] && [ -z "$8" ] && [ -z "$9" ] && [ -z "$10" ] && [ -z "$11" ] && [ -z "$12" ] ; then
		"${PATH_DWA_RUNTIME}/$EXENM" installer.py
	else
		"${PATH_DWA_RUNTIME}/$EXENM" installer.py $3 $4 $5 $6 $7 $8 $9 $10 $11 $12
	fi
else
	rm -r -f "${PATH_DWA}/runtime"
	PYPTH=$(which "python3" 2>/dev/null)
	check_py_ver $PYPTH
	if [ "$?" = "1" ]; then
		PYPTH=$(which "python2.7" 2>/dev/null)
		check_py_ver $PYPTH
    	if [ "$?" = "1" ]; then
			echo "Error: Missing Python. Required version 3.6+ or 2.7."
			exit 1
		fi
	fi
	if [ -z "$3" ] && [ -z "$4" ] && [ -z "$5" ] && [ -z "$6" ] && [ -z "$7" ] && [ -z "$8" ] && [ -z "$9" ] && [ -z "$10" ] && [ -z "$11" ] && [ -z "$12" ] ; then
		"${PYPTH}" installer.py
	else
		"${PYPTH}" installer.py $3 $4 $5 $6 $7 $8 $9 $10 $11 $12
	fi
fi

if [ -e "${PATH_DWA}/runasadmin.install" ]; then
	rm -r -f "${PATH_DWA}/runasadmin.install"
	if [ "$(id -u)" != "0" ]; then
		open -n -a $2 --args runasadmin "${PATH_DWA}" "$2" "GOTOOPT=install"
	else
		#REMOVE TEMP PATH
		rm -r -f "${PATH_DWA}"
	fi
else
	#REMOVE TEMP PATH
	rm -r -f "${PATH_DWA}"	
fi
exit 0
	

